package cn.dida.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import cn.dida.util.ValidUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.dida.exception.BizzException;
import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.LgsNode;
import cn.dida.model.Pageable;
import cn.dida.model.UserSession;
import cn.dida.service.LgsNodeService;

/**
 * <p>节点管理</p>
 * @auther lisha
 * @date 2017-2-8 14:45:12
 */
@Controller
public class LgsNodeController extends BaseController{

	@Autowired
	private LgsNodeService lgsNodeService;
	
	/**
	 * 增加节点
	 * @param request
	 * @param lgsNode 节点实体类
	 * @return HttpResponseBodyWrapper 封装操作标记（ true新增成功，false新增失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PostMapping("/lgsNode")
    public HttpResponseBodyWrapper add(HttpServletRequest request, @RequestBody LgsNode lgsNode) throws Exception {
        
        UserSession userSession = getUserSession(request);
        lgsNode.setCompanyId(userSession.getCompanyId());
        lgsNode.setcAdmin(userSession.getAccount());

        if (lgsNode.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入节点名称");
        }
        if (!Pattern.matches(ValidUtil.WENZI_PATTERN,lgsNode.getName())) {
            throw new BizzException(BizzException.error_code_invalid_params, "节点名称仅限汉字、数字、字母！");
        }
        
        Boolean flag = lgsNodeService.isExistsNode(userSession.getCompanyId(), lgsNode.getName());
        if(flag){
        	throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+lgsNode.getName()+"】的节点");
        }

        lgsNode.setName(StringUtils.trimToNull(lgsNode.getName()));
        Boolean result = lgsNodeService.insertLgsNode(lgsNode);
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 修改节点
	 * @param request
	 * @param lgsNode 节点实体类
	 * @return HttpResponseBodyWrapper 封装操作标记（ true更新成功，false更新失败）
	 * @throws Exception
	 */
	@ResponseBody
    @PutMapping("/lgsNode/{id}")
    public HttpResponseBodyWrapper update(HttpServletRequest request, @RequestBody LgsNode lgsNode) throws Exception {
		UserSession userSession = getUserSession(request);
		int companyId = userSession.getCompanyId();
        
		lgsNode.setCompanyId(companyId);
		
        if (lgsNode.getName() == null) {
            throw new BizzException(BizzException.error_code_invalid_params, "请输入节点名称");
        }
        if (!Pattern.matches(ValidUtil.WENZI_PATTERN,lgsNode.getName())) {
            throw new BizzException(BizzException.error_code_invalid_params, "节点名称仅限汉字、数字、字母！");
        }
        LgsNode temp = lgsNodeService.getLgsNodeById(lgsNode.getId(), companyId);
        if(temp != null && !(temp.getName().equals(lgsNode.getName()))){
        	if(lgsNodeService.isExistsNode(companyId, lgsNode.getName())){
        		throw new BizzException(BizzException.error_code_invalid_params, "已存在名称为【"+lgsNode.getName()+"】的节点");
        	}
        }
        
        lgsNode.setName(StringUtils.trimToNull(lgsNode.getName()));
        Boolean result = lgsNodeService.updateLgsNode(companyId, lgsNode);
        
        return new HttpResponseBodyWrapper(result);
    }
	
	/**
	 * 节点管理列表
	 * @param request
	 * @param name 节点名称
	 * @param page 分页游标
	 * @return ModelAndView 节点管理列表页面
	 * @throws Exception
	 */
	@GetMapping("/lgsNode")
    public ModelAndView list(HttpServletRequest request, String name, Integer type, Integer sta, Integer page) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        name = StringUtils.trimToEmpty(name);
        Pageable<LgsNode> lgsNodeList = lgsNodeService.query(name, type, sta, userSession.getCompanyId(), page);

        model.put("lgsNodeList", lgsNodeList);
        model.put("name", name);
        model.put("type", type);
        model.put("sta", sta);
        return new ModelAndView("lgsNode_list").addAllObjects(model);
    }
	
	/**
	 * 获取节点详情
	 * @param request
	 * @param id 节点id
	 * @return HttpResponseBodyWrapper 封装单个节点管理实体数据
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping("/lgsNode/{id}")
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, @PathVariable int id) throws Exception {
		UserSession userSession = getUserSession(request);
		LgsNode lgsNode = lgsNodeService.getLgsNodeById(id, userSession.getCompanyId());
        return new HttpResponseBodyWrapper(lgsNode);
    }
	
	/**
     * 节点列表 （单据页面用）
     * @param request
     * @param state 状态（1：正常、0：已停用）
     * @param 
     * @return 
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "/lgsNode/getNodeList", produces = MediaType.APPLICATION_JSON_VALUE)
    public HttpResponseBodyWrapper getBrand(HttpServletRequest request, Integer state) throws Exception {
        Map<String, Object> model = new HashMap<String, Object>();
        UserSession userSession = getUserSession(request);
        List<LgsNode> nodeList = lgsNodeService.getNodeList(userSession.getCompanyId(), state);
        model.put("nodeList", nodeList);
        return new HttpResponseBodyWrapper(nodeList);
    }


    /**
     * 获取该公司未被关联的  erp适用单据表
     * @return
     */
    @ResponseBody
    @GetMapping("/getBiztype")
    public HttpResponseBodyWrapper getBiztype(HttpServletRequest request){
        UserSession userSession = getUserSession(request);
        List<Map<String,Object>> list = lgsNodeService.getBiztype(userSession.getCompanyId());
        return new HttpResponseBodyWrapper(list);
    }


    /**
     *获取编辑页 ERP适用单据
	 * @param nodeId
	 * @return
             */
    @ResponseBody
    @GetMapping("/getBiztypeByEeit")
    public HttpResponseBodyWrapper getBiztypeByNode(HttpServletRequest request,Integer nodeId){

        Map<String,Object> map=new HashMap<>();
        UserSession userSession = getUserSession(request);
        List<Map<String,Object>> list = lgsNodeService.getBiztype(userSession.getCompanyId());
        List<Map<String,Object>> li = lgsNodeService.getBiztypeByNode(nodeId,userSession.getCompanyId());

        map.put("list",list);
        map.put("secList",li);

        return new HttpResponseBodyWrapper(map);
    }
}
